package com.vdg.fps;

import java.util.ArrayList;
import java.util.Collections;

import android.app.Activity;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Intent;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.widget.SearchView;
import com.actionbarsherlock.widget.SearchView.OnQueryTextListener;
import com.actionbarsherlock.widget.SearchView.OnSuggestionListener;
import com.vdg.R;
import com.vdg.fps.adapter.ListMembersPostingAdapter;
import com.vdg.fps.adapter.ListMembersPostingAdapter.POST_TYPE;
import com.vdg.fps.config.FPSConfig;
import com.vdg.fps.data.FaceBookAccount;
import com.vdg.fps.data.FaceBookMessage;
import com.vdg.fps.data.FaceBookPostResult;
import com.vdg.fps.data.GroupsData;
import com.vdg.fps.data.MemberPostingData;
import com.vdg.fps.data.SettingData;
import com.vdg.fps.listener.OnPostResultListener;
import com.vdg.fps.listener.OnRequestListnener;
import com.vdg.fps.services.FPSService;
import com.vdg.fps.services.FPSService.LocalBinder;
import com.vdg.fps.ui.view.TextViewPlus;
import com.vdg.fps.ulti.Utilities;
import com.vdg.ui.fragment.AccountsFragment;

public class PostMessageActivity extends BaseActivity implements
		ActionBar.OnNavigationListener {
	private FPSService mService;
	private ArrayList<MemberPostingData> mListMembers;
	private ListMembersPostingAdapter mListMembersAdapter;
	private ListView mListView;
	private TextViewPlus mTxvFetchMembers;
	private TextViewPlus mTxvImportIDS;
	private FrameLayout mFrmLoadingDialog;
	private MemberPostingData mSelectData;
	private GroupsData mGroupsData;
	private TextViewPlus mTxvTitle;
	private LinearLayout mDevPostID;
	private LinearLayout mDevStatus;
	private CheckBox mChbCheckAll;
	private LinearLayout mDevCheckAll;
	private TextViewPlus mTxvPostID;
	private TextViewPlus mTxvStatus;
	private Handler mHandler;
	private boolean mStopPost = false;
	int mAccountIndex;
	private FaceBookAccount mFaceBookAccount;

	@Override
	public void onServiceConnected(ComponentName name, IBinder service) {
		// TODO Auto-generated method stub
		super.onServiceConnected(name, service);
		LocalBinder binder = (LocalBinder) service;
		mService = binder.getService();
		initView();
	}

	@Override
	public void onServiceDisconnected(ComponentName name) {
		// TODO Auto-generated method stub
		super.onServiceDisconnected(name);
		mService = null;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		setTheme(R.style.Theme_Sherlock_Light_DarkActionBar);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.post_message_layout);
		ArrayAdapter<CharSequence> list = ArrayAdapter.createFromResource(this,
				R.array.locations, R.layout.sherlock_spinner_item);
		list.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);
		getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
		getSupportActionBar().setListNavigationCallbacks(list, this);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		getSupportActionBar().setHomeButtonEnabled(true);
		getSupportActionBar().setBackgroundDrawable(
				new ColorDrawable(getResources()
						.getColor(R.color.top_bar_color)));
	}

	private void initView() {
		mListMembers = new ArrayList<MemberPostingData>();
		mListView = (ListView) findViewById(R.id.liv_members);
		mListMembersAdapter = new ListMembersPostingAdapter(this, 0,
				mListMembers, POST_TYPE.POST);
		mListView.setAdapter(mListMembersAdapter);
		mListView.setStackFromBottom(false);
		mTxvFetchMembers = (TextViewPlus) findViewById(R.id.txv_fecth_members);
		mTxvImportIDS = (TextViewPlus) findViewById(R.id.txv_import_ids);
		mFrmLoadingDialog = (FrameLayout) findViewById(R.id.frm_loading_dialog);
		mTxvTitle = (TextViewPlus) findViewById(R.id.txv_title);
		mDevPostID = (LinearLayout) findViewById(R.id.dev_post_id);
		mDevCheckAll = (LinearLayout) findViewById(R.id.dev_selected);
		mChbCheckAll = (CheckBox) findViewById(R.id.chb_select_all);
		mTxvPostID = (TextViewPlus) findViewById(R.id.txv_post_id);
		mTxvStatus = (TextViewPlus) findViewById(R.id.txv_status);
		mDevStatus = (LinearLayout) findViewById(R.id.dev_status);
		mHandler = new Handler();
		mChbCheckAll.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				// TODO Auto-generated method stub
				mListMembersAdapter.setSelectAll(isChecked);
				notifyToListView();
			}
		});
		mTxvImportIDS.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mListMembers != null && mListMembers.size() != 0) {
					mListMembers.clear();
				}
				ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
				CharSequence copyedText = clipboard.getText();
				if (copyedText != null && !copyedText.toString().equals("")) {
					mListMembers.addAll(MemberPostingData
							.getListFromString(copyedText.toString()));
					Collections.sort(mListMembers);
					mListMembersAdapter = new ListMembersPostingAdapter(
							PostMessageActivity.this, 0, mListMembers,
							POST_TYPE.POST);
					mListView.setAdapter(mListMembersAdapter);
					if (!mTxvFetchMembers.getText().toString()
							.equals("Select To Post")) {
						mListMembersAdapter.setIsSelected(true);
					}
					mListMembersAdapter.notifyDataSetChanged();
				}
			}
		});

		mTxvFetchMembers.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (mTxvFetchMembers.getText().toString()
						.equals("Select To Post")) {
					mDevPostID.setVisibility(View.GONE);
					mTxvStatus.setVisibility(View.GONE);
					mTxvPostID.setVisibility(View.GONE);
					mDevStatus.setVisibility(View.GONE);
					mChbCheckAll.setVisibility(View.VISIBLE);
					mDevCheckAll.setVisibility(View.VISIBLE);
					mListMembersAdapter.setIsSelected(true);
					notifyToListView();
					mTxvFetchMembers.setText("Post Message");
				} else {
					if (mTxvFetchMembers.getText().toString()
							.equals("Stop Post")) {
						mStopPost = true;
						mTxvFetchMembers.setText("Select To Post");
						mTxvFetchMembers.setBackgroundDrawable(getResources()
								.getDrawable(R.drawable.btn_side_menu));
						return;
					}
					if (mListMembersAdapter.getSelectedData() == null
							|| mListMembersAdapter.getSelectedData().size() == 0) {
						Utilities.showToast(
								"Please select a member to post message",
								PostMessageActivity.this);
						return;
					}
					Intent intent = new Intent(PostMessageActivity.this,
							MessageActivity.class);
					startActivityForResult(intent, 0);
					mDevPostID.setVisibility(View.VISIBLE);
					mTxvStatus.setVisibility(View.VISIBLE);
					mTxvPostID.setVisibility(View.VISIBLE);
					mDevStatus.setVisibility(View.VISIBLE);
					mChbCheckAll.setVisibility(View.GONE);
					mDevCheckAll.setVisibility(View.GONE);
					mListMembersAdapter.setIsSelected(false);
					notifyToListView();
					mTxvFetchMembers.setText("Select To Post");
				}
			}
		});
		Intent intent = getIntent();
		if (intent != null) {
			mGroupsData = (GroupsData) intent
					.getSerializableExtra(FetchGroupsListActivity.GROUP_KEY);
			mAccountIndex = (Integer) intent.getIntExtra(
					AccountsFragment.FACE_BOOK_ACCOUNT_KEY, -1);
			if (mAccountIndex != -1) {
				if (mService.getFacebookAccount(mAccountIndex) != null) {
					mFaceBookAccount = mService
							.getFacebookAccount(mAccountIndex);
				}
			}
		}
		setUIFont();
		registerForContextMenu(mListView);
		registerForContextMenu(mListView);
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				mSelectData = mListMembersAdapter.getItem(position);
				// mMenu.removeItem(3);
				openContextMenu(mListView);
				// registerForContextMenu(mListView);
				// openContextMenu(view);
				// unregisterForContextMenu(view);
			}
		});
		mListView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				mSelectData = mListMembersAdapter.getItem(position);
				return false;
			}

		});
	}

	private void setUIFont() {
		Typeface type = Typeface
				.createFromAsset(getAssets(), FPSConfig.UI_FONT);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		// TODO Auto-generated method stub
		menu.setHeaderTitle("Menu");
		menu.add(0, 1, 1, "View this profile on browser");
		menu.add(0, 3, 2, "View This Post");
		menu.add(0, 2, 2, "Copy ID");
		menu.add(0, 4, 3, "Copy Name");
		menu.add(0, 5, 4, "Export selected IDs to clipboard");
		menu.add(0, 6, 5, "Export selected IDs to sdCard");
		super.onCreateContextMenu(menu, v, menuInfo);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		if (item.getTitle().equals("View this profile on browser")) {
			Intent browserIntent = new Intent(Intent.ACTION_VIEW,
					Uri.parse("https://m.facebook.com/" + mSelectData.getID()));
			startActivity(browserIntent);
		}
		if (item.getTitle().equals("Copy ID")) {
			ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
			clipboard.setText(mSelectData.getID());
			Utilities.showToast("Coppy ID to clipboard sucessfully!",
					PostMessageActivity.this);
		}
		if (item.getTitle().equals("View This Post")) {
			if (mSelectData != null && mSelectData.getPostID() != null
					&& !mSelectData.getID().equals("")) {
				Intent browserIntent = new Intent(Intent.ACTION_VIEW,
						Uri.parse("https://m.facebook.com/"
								+ mFaceBookAccount.getID() + "/posts/"
								+ mSelectData.getPostID()));
				startActivity(browserIntent);
			} else {
				Utilities.showToast("No Posts!", PostMessageActivity.this);
			}
		}
		if (item.getTitle().equals("Copy Name")) {
			ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
			clipboard.setText(mSelectData.getName());
			Utilities.showToast("Coppy Name to clipboard sucessfully!",
					PostMessageActivity.this);
		}
		if (item.getTitle().equals("Export all IDs to clipboard")) {
			ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
			clipboard.setText(MemberPostingData.toString(mListMembersAdapter
					.getDisplayData()));
			Utilities.showToast("Coppy all IDs to clipboard sucessfully!",
					PostMessageActivity.this);
		}
		if (item.getTitle().equals("Export selected IDs to sdCard")) {
			Utilities.startSaveFile(FPSConfig.MEMBER_IN_GROUP,
					mSelectData.getName() + ".txt", PostMessageActivity.this,
					mSelectData.toString().getBytes());
		}
		if (item.getTitle().equals("Export all IDs to sdCard")) {
			Utilities.startSaveFile(
					FPSConfig.MEMBER_IN_GROUP,
					mGroupsData.getName() + "_all_members.txt",
					PostMessageActivity.this,
					MemberPostingData.toString(
							mListMembersAdapter.getDisplayData()).getBytes());
		}
		return super.onContextItemSelected(item);
	}

	private void notifyToListView(MemberPostingData data) {
		int start = mListView.getFirstVisiblePosition();
		for (int i = start, j = mListView.getLastVisiblePosition(); i <= j; i++) {
			String id = ((MemberPostingData) (mListView.getItemAtPosition(i)))
					.getID();
			if (id != null && id.equals(data.getID())) {
				View view = mListView.getChildAt(i - start);
				mListView.getAdapter().getView(i, view, mListView);
				break;
			}
		}
	}

	private void notifyToListView() {
		int start = mListView.getFirstVisiblePosition();
		for (int i = start, j = mListView.getLastVisiblePosition(); i <= j; i++) {
			View view = mListView.getChildAt(i - start);
			mListView.getAdapter().getView(i, view, mListView);
		}
	}

	public MemberPostingData getMember(String id) {
		for (MemberPostingData data : mListMembers) {
			if (data.getID().equals(id)) {
				return data;
			}
		}
		return null;
	}

	private boolean mPostFinish;

	private void setStateToWaiting() {
		if (mListMembersAdapter != null) {
			for (final MemberPostingData member : mListMembersAdapter
					.getSelectedData()) {
				mPostFinish = false;
				member.setStatus("Waiting");
				mHandler.post(new Runnable() {

					@Override
					public void run() {
						notifyToListView(member);
					}
				});
			}
		}
	}

	public void startCountDownTimer(final long Time,
			final MemberPostingData data) {
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				new CountDownTimer(Time, 1000) {
					public void onTick(long millisUntilFinished) {
						data.setStatus("Delaying "
								+ ((int) millisUntilFinished / 1000) + "s");
						runOnUiThread(new Runnable() {
							public void run() {
								notifyToListView(data);
							}
						});
					}

					public void onFinish() {
					}
				}.start();
			}
		});
	}

	private boolean isFinishDelay;
	private boolean isEndPost;

	public void startPost(final FaceBookMessage msg) {
		(new Thread() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				isEndPost = false;
				if (mListMembersAdapter != null) {
					setStateToWaiting();
					if (mListMembersAdapter.getSelectedData() != null) {
						mHandler.post(new Runnable() {

							@Override
							public void run() {
								// TODO Auto-generated method stub
								mTxvFetchMembers.setText("Stop Post");
								mTxvFetchMembers
										.setBackgroundDrawable(getResources()
												.getDrawable(R.drawable.bnt_red));
							}
						});
						boolean isfirst = true;
						for (final MemberPostingData member : mListMembersAdapter
								.getSelectedData()) {
							isFinishDelay = false;
							final int delayTime;
							mPostFinish = false;
							if (member == null) {
								return;
							}
							if (mStopPost) {
								member.setStatus("Stopped");
								mHandler.post(new Runnable() {

									@Override
									public void run() {
										notifyToListView(member);
									}
								});
								continue;
							}
							if (!isfirst) {
								delayTime = SettingData.getInstance(
										PostMessageActivity.this)
										.getRandomDelaySecondTime();
								Log.v("debug", "delay = " + delayTime);
								member.setStatus("Delay " + delayTime + "s");
								mHandler.post(new Runnable() {
									@Override
									public void run() {
										notifyToListView(member);
									}
								});
								mHandler.post(new Runnable() {
									@Override
									public void run() {
										// TODO Auto-generated method stub
										new CountDownTimer(delayTime * 1000,
												1000) {
											public void onTick(
													long millisUntilFinished) {
												if (mStopPost) {
													isFinishDelay = true;
													try {
														stop();
													} catch (Exception e) {
														e.printStackTrace();
													}
													return;
												}
												member.setStatus("Delay "
														+ ((int) millisUntilFinished / 1000)
														+ "s");
												runOnUiThread(new Runnable() {
													public void run() {
														notifyToListView(member);
													}
												});
											}

											public void onFinish() {
												isFinishDelay = true;
											}
										}.start();
									}
								});
								while (!isFinishDelay) {
									try {
										sleep(100);
									} catch (InterruptedException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
								}
							}
							if (mStopPost) {
								member.setStatus("Stopped");
								mHandler.post(new Runnable() {

									@Override
									public void run() {
										notifyToListView(member);
									}
								});
								continue;
							}
							isfirst = false;
							member.setStatus("Posting");
							mHandler.post(new Runnable() {

								@Override
								public void run() {
									notifyToListView(member);
								}
							});
							mFaceBookAccount
									.GetFBDTSG(new OnRequestListnener() {
										@Override
										public void onSuccess(String response) {
											// TODO Auto-generated method
											// stub
											mFaceBookAccount.postToWallID(
													response, member.getID(),
													msg,
													new OnPostResultListener() {

														@Override
														public void onResult(
																final FaceBookPostResult result) {
															// TODO
															// Auto-generated
															// method stub
															member.setPostID(result
																	.getPostID());
															member.setStatus(result
																	.getStatus());
															mHandler.post(new Runnable() {

																@Override
																public void run() {
																	notifyToListView(member);
																	if (isEndPost) {
																		mTxvFetchMembers
																				.setText("Select To Post");
																	}
																}
															});
															mPostFinish = true;
														}
													});
										}

										@Override
										public void onFailed(final int errorCode) {
											// TODO Auto-generated method
											// stub
											mHandler.post(new Runnable() {

												@Override
												public void run() {
													Utilities
															.showError(
																	errorCode,
																	PostMessageActivity.this);
													if (isEndPost) {
														mTxvFetchMembers
																.setText("Select To Post");
													}
												}
											});
											mPostFinish = false;
										}
									});
							while (!mPostFinish) {
								try {
									sleep(100);
								} catch (InterruptedException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
						}
						// do what you have to do here
					}
				}
				isEndPost = true;
				super.run();
			}
		}).start();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if (requestCode == 0) {
			if (resultCode == Activity.RESULT_OK) {
				if (data == null
						|| data.getSerializableExtra(MessageActivity.MESSAGE_KEY) == null) {
					return;
				}
				final FaceBookMessage msg = (FaceBookMessage) data
						.getSerializableExtra(MessageActivity.MESSAGE_KEY);
				if (msg == null) {
					return;
				}
				mStopPost = false;
				startPost(msg);
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		// Create the search view
		SearchView searchView = new SearchView(getSupportActionBar()
				.getThemedContext());
		searchView.setQueryHint("Search for name...");
		searchView.setOnQueryTextListener(new OnQueryTextListener() {

			@Override
			public boolean onQueryTextSubmit(String query) {
				// TODO Auto-generated method stub
				return false;
			}

			@Override
			public boolean onQueryTextChange(String newText) {
				// TODO Auto-generated method stub
				if (mListMembersAdapter != null) {
					mListMembersAdapter.filter(newText);
				}
				return false;
			}
		});
		searchView.setOnSuggestionListener(new OnSuggestionListener() {

			@Override
			public boolean onSuggestionSelect(int position) {
				// TODO Auto-generated method stub
				return false;
			}

			@Override
			public boolean onSuggestionClick(int position) {
				// TODO Auto-generated method stub
				return false;
			}
		});

		menu.add("Search")
				.setActionView(searchView)
				.setIcon(getResources().getDrawable(R.drawable.btn_search))
				.setShowAsAction(
						MenuItem.SHOW_AS_ACTION_IF_ROOM
								| MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);

		return true;
	}

	@Override
	public boolean onNavigationItemSelected(int itemPosition, long itemId) {
		// TODO Auto-generated method stub
		return false;
	}
}
